<?php

namespace app\middleware;

use Dsxwk\Framework\Utils\Trace\Trace;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class TraceId implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        $traceId = $request->header('X-Trace-Id') ?? null;
        Trace::init($traceId);
        $response = $handler($request);

        return $response->withHeaders(
            [
                'X-Trace-Id' => Trace::get(),
                'Content-Type' => 'application/json',
            ]
        );
    }
}
